package com.hup.minicontroller.common;

import java.util.concurrent.*;

/**
 * @author hugan
 * @date 2021/5/23
 */
public class SubThreadHandler {

    private final ScheduledExecutorService executor;

    public SubThreadHandler() {
        executor = Executors.newSingleThreadScheduledExecutor();
    }

    public void execute(Runnable task) {
        executor.execute(task);
    }

    public ScheduledFuture<?> schedule(Runnable command, long delay) {
        return executor.schedule(command, delay, TimeUnit.MILLISECONDS);
    }

    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
        return executor.schedule(command, delay, unit);
    }

    public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
        return executor.schedule(callable, delay, unit);
    }

    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        return executor.scheduleAtFixedRate(command, initialDelay, period, unit);
    }

    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        return executor.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    }

    /**
     * @param quitSafely true-等待之前的消息处理完后再退出,false-马上退出,不处理剩余的消息
     */
    public void doTerminate(boolean quitSafely) {
        //可能不对?未深究
        if (quitSafely) {
            executor.shutdown();
        } else {
            executor.shutdownNow();
        }
    }

}
